<template>
  <div class="user-card" v-if="userStats || loading">
    <!-- 加载状态 -->
    <div v-if="loading && !userStats" class="loading-state">
      <svg viewBox="0 0 24 24" width="40" height="40" fill="currentColor" class="spin">
        <path d="M12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2zm0 18c-4.41 0-8-3.59-8-8s3.59-8 8-8 8 3.59 8 8-3.59 8-8 8zm0-14c-3.31 0-6 2.69-6 6h2c0-2.21 1.79-4 4-4V6z"/>
      </svg>
      <p>加载中...</p>
    </div>
    
    <!-- 用户头部信息 -->
    <div v-if="userStats" class="user-header">
      <div class="user-avatar-large">
        <img 
          v-if="userStats.avatar" 
          :src="getAvatarUrl(userStats.avatar)" 
          alt="头像"
        />
        <span v-else class="avatar-placeholder-large">
          {{ userStats.nickname?.charAt(0) || 'U' }}
        </span>
      </div>
      <div class="user-info">
        <div class="user-name">
          {{ userStats.nickname || '未命名用户' }}
          <svg v-if="userStats.isVerified" class="verified-icon" viewBox="0 0 24 24" width="16" height="16" fill="currentColor">
            <path d="M9 16.17L4.83 12l-1.42 1.41L9 19 21 7l-1.41-1.41z"/>
          </svg>
        </div>
        <div class="user-id">{{ userStats.username || `ID: ${userStats.id}` }}</div>
        <div class="user-location" v-if="userStats.location">
          <svg viewBox="0 0 24 24" width="12" height="12" fill="currentColor">
            <path d="M12 2C8.13 2 5 5.13 5 9c0 5.25 7 13 7 13s7-7.75 7-13c0-3.87-3.13-7-7-7zm0 9.5c-1.38 0-2.5-1.12-2.5-2.5s1.12-2.5 2.5-2.5 2.5 1.12 2.5 2.5-1.12 2.5-2.5 2.5z"/>
          </svg>
          {{ userStats.location }}
        </div>
      </div>
    </div>

    <!-- 统计信息 -->
    <div v-if="userStats" class="user-stats">
      <div class="stat-item">
        <div class="stat-label">被阅读</div>
        <div class="stat-value">{{ formatNumber(userStats.totalViews) }}</div>
      </div>
      <div class="stat-item">
        <div class="stat-label">被点赞</div>
        <div class="stat-value">{{ formatNumber(userStats.totalLikes) }}</div>
      </div>
      <div class="stat-item">
        <div class="stat-label">被收藏</div>
        <div class="stat-value">{{ formatNumber(userStats.totalFavorites) }}</div>
      </div>
      <div class="stat-item">
        <div class="stat-label">关注者</div>
        <div class="stat-value">{{ formatNumber(userStats.followers) }}</div>
      </div>
    </div>

    <!-- 操作按钮 -->
    <div v-if="userStats" class="user-actions">
      <button 
        v-if="!isCurrentUser"
        class="btn-follow"
        :class="{ followed: userStats.isFollowed }"
        @click="handleFollow"
      >
        {{ userStats.isFollowed ? '已关注' : '+ 关注' }}
      </button>
      <button 
        v-if="!isCurrentUser"
        class="btn-message"
        @click="handleMessage"
      >
        <svg viewBox="0 0 24 24" width="16" height="16" fill="currentColor">
          <path d="M20 2H4c-1.1 0-2 .9-2 2v18l4-4h14c1.1 0 2-.9 2-2V4c0-1.1-.9-2-2-2zm0 14H6l-2 2V4h16v12z"/>
        </svg>
        私信
      </button>
      <button 
        v-if="isCurrentUser"
        class="btn-profile"
        @click="goToProfile"
      >
        查看我的主页
      </button>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { useUserStore } from '../stores/user'
import { getUserStats, followUser } from '../api/user'
import { getAvatarUrl } from '../utils/url'

const props = defineProps({
  userId: {
    type: Number,
    required: true
  }
})

const emit = defineEmits(['message'])

const router = useRouter()
const userStore = useUserStore()

const userStats = ref(null)
const loading = ref(false)

const isCurrentUser = computed(() => {
  const result = userStore.userInfo?.id === props.userId
  console.log('UserCard - 当前用户ID:', userStore.userInfo?.id)
  console.log('UserCard - 查看的用户ID:', props.userId)
  console.log('UserCard - 是否是当前用户:', result)
  return result
})

onMounted(() => {
  loadUserStats()
})

async function loadUserStats() {
  loading.value = true
  try {
    const res = await getUserStats(props.userId)
    if (res.code === 200) {
      userStats.value = res.data
      // 🎯 关键修改：无论后端返回什么，都统一显示"定位中..."，避免"哈佛→四川省"的突变
      userStats.value.location = '定位中...'
    }
  } catch (error) {
    console.error('获取用户统计失败:', error)
    // 使用模拟数据
    userStats.value = {
      id: props.userId,
      nickname: '用户',
      username: `user_${props.userId}`,
      avatar: null,
      location: '定位中...',
      totalViews: 14660,
      totalLikes: 1400,
      totalFavorites: 6100,
      followers: 1200,
      isFollowed: false,
      isVerified: false
    }
  } finally {
    loading.value = false
    // 无论成功或失败，都用前端IP定位覆盖location
    loadUserLocation()
  }
}

// 前端IP定位 - 使用多个API保证成功率
async function loadUserLocation() {
  if (!userStats.value) return
  
  // 方法1: 使用高德地图IP定位（免费，支持CORS）
  try {
    const response = await fetch('https://restapi.amap.com/v3/ip?key=c3d875fba856e58794ab205733e0e118')
    const data = await response.json()
    
    if (data.status === '1' && data.province) {
      // 成功获取到省份
      userStats.value.location = data.province
      console.log('✅ IP定位成功 (高德):', data.province, '|', data.city)
      return
    }
  } catch (error) {
    console.warn('高德IP定位失败，尝试备用方案...', error)
  }
  
  // 方法2: 使用百度地图IP定位（备用）- 通过代理服务器避免CORS
  try {
    // 使用JSONP方式调用百度API，避免CORS问题
    const script = document.createElement('script')
    script.src = `https://api.map.baidu.com/location/ip?ak=C93b5178d7a8ebdb830b9b557abce78b&coor=bd09ll&callback=handleBaiduLocation`
    
    // 创建全局回调函数
    window.handleBaiduLocation = (data) => {
      if (data.status === 0 && data.content?.address_detail?.province) {
        userStats.value.location = data.content.address_detail.province
        console.log('✅ IP定位成功 (百度):', data.content.address_detail.province)
      }
      // 清理
      document.head.removeChild(script)
      delete window.handleBaiduLocation
    }
    
    document.head.appendChild(script)
    
    // 设置超时
    setTimeout(() => {
      if (window.handleBaiduLocation) {
        document.head.removeChild(script)
        delete window.handleBaiduLocation
        throw new Error('百度API超时')
      }
    }, 5000)
    
    return
  } catch (error) {
    console.warn('百度IP定位失败，尝试备用方案...', error)
  }
  
  // 方法3: 使用 ipapi.co（国际免费API）
  try {
    const response = await fetch('https://ipapi.co/json/')
    const data = await response.json()
    
    if (data.region) {
      // 将英文地名转换为中文（简单映射）
      const provinceMap = {
        'Sichuan': '四川省',
        'Beijing': '北京市',
        'Shanghai': '上海市',
        'Guangdong': '广东省',
        'Zhejiang': '浙江省',
        'Jiangsu': '江苏省'
        // 可以添加更多映射
      }
      const province = provinceMap[data.region] || data.region
      userStats.value.location = province
      console.log('✅ IP定位成功 (ipapi):', province)
      return
    }
  } catch (error) {
    console.warn('ipapi定位失败，使用默认值', error)
  }
  
  // 所有方法都失败，使用默认值
  userStats.value.location = '中国'
  console.warn('⚠️ 所有IP定位方法都失败，使用默认值: 中国')
}

async function handleFollow() {
  try {
    const res = await followUser(props.userId)
    if (res.code === 200) {
      userStats.value.isFollowed = res.data.isFollowed
      if (res.data.isFollowed) {
        userStats.value.followers++
      } else {
        userStats.value.followers--
      }
    }
  } catch (error) {
    console.error('关注失败:', error)
  }
}

function handleMessage() {
  emit('message', userStats.value)
}

function goToProfile() {
  router.push('/profile')
}

function formatNumber(num) {
  if (!num) return '0'
  if (num >= 10000) {
    return (num / 10000).toFixed(1) + 'W'
  }
  if (num >= 1000) {
    return (num / 1000).toFixed(1) + 'K'
  }
  return num.toString()
}
</script>

<style scoped lang="scss">
.user-card {
  width: 320px;
  background: white;
  border-radius: 12px;
  box-shadow: 0 8px 24px rgba(0, 0, 0, 0.15);
  padding: 20px;
  
  .loading-state {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    padding: 40px 20px;
    min-height: 200px;
    
    svg.spin {
      animation: spin 1s linear infinite;
      color: #667eea;
      margin-bottom: 16px;
    }
    
    p {
      font-size: 14px;
      color: #8c959f;
      margin: 0;
    }
  }
  
  @keyframes spin {
    from {
      transform: rotate(0deg);
    }
    to {
      transform: rotate(360deg);
    }
  }
  
  .user-header {
    display: flex;
    gap: 16px;
    margin-bottom: 20px;
    
    .user-avatar-large {
      width: 64px;
      height: 64px;
      flex-shrink: 0;
      
      img {
        width: 100%;
        height: 100%;
        border-radius: 50%;
        object-fit: cover;
      }
      
      .avatar-placeholder-large {
        width: 100%;
        height: 100%;
        border-radius: 50%;
        background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
        color: white;
        display: flex;
        align-items: center;
        justify-content: center;
        font-size: 24px;
        font-weight: bold;
      }
    }
    
    .user-info {
      flex: 1;
      min-width: 0;
      
      .user-name {
        font-size: 18px;
        font-weight: 600;
        color: #24292f;
        margin-bottom: 4px;
        display: flex;
        align-items: center;
        gap: 6px;
        
        .verified-icon {
          color: #1890ff;
        }
      }
      
      .user-id {
        font-size: 13px;
        color: #8c959f;
        margin-bottom: 6px;
      }
      
      .user-location {
        display: flex;
        align-items: center;
        gap: 4px;
        font-size: 12px;
        color: #57606a;
        
        svg {
          flex-shrink: 0;
        }
      }
    }
  }
  
  .user-stats {
    display: grid;
    grid-template-columns: repeat(4, 1fr);
    gap: 12px;
    margin-bottom: 20px;
    padding: 16px;
    background: #f6f8fa;
    border-radius: 8px;
    
    .stat-item {
      text-align: center;
      
      .stat-label {
        font-size: 12px;
        color: #57606a;
        margin-bottom: 4px;
      }
      
      .stat-value {
        font-size: 16px;
        font-weight: 600;
        color: #24292f;
      }
    }
  }
  
  .user-actions {
    display: flex;
    gap: 10px;
    
    button {
      flex: 1;
      padding: 8px 16px;
      border-radius: 6px;
      font-size: 14px;
      font-weight: 500;
      cursor: pointer;
      transition: all 0.2s;
      display: flex;
      align-items: center;
      justify-content: center;
      gap: 6px;
      
      svg {
        flex-shrink: 0;
      }
    }
    
    .btn-follow {
      background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
      color: white;
      border: none;
      
      &:hover {
        transform: translateY(-1px);
        box-shadow: 0 4px 12px rgba(102, 126, 234, 0.3);
      }
      
      &.followed {
        background: #e9ecef;
        color: #57606a;
        
        &:hover {
          background: #dee2e6;
        }
      }
    }
    
    .btn-message {
      background: white;
      color: #24292f;
      border: 1px solid #d0d7de;
      
      &:hover {
        background: #f6f8fa;
        border-color: #c1c7cd;
      }
    }
    
    .btn-profile {
      background: white;
      color: #667eea;
      border: 1px solid #667eea;
      
      &:hover {
        background: #f6f8fa;
      }
    }
  }
}
</style>

